provider "alicloud" {
  profile = "default"
  version = "1.151.0"
}

variable "name" {
  default = "xiaojiu"
}

data "alicloud_zones" "default" {
  available_resource_creation = "KVStore"
}

resource "alicloud_vpc" "default" {
  vpc_name       = var.name
  cidr_block = "172.16.0.0/16"
}

resource "alicloud_vswitch" "default" {
  vpc_id       = alicloud_vpc.default.id
  cidr_block   = "172.16.0.0/24"
  zone_id      = data.alicloud_zones.default.zones[0].id
  vswitch_name = var.name
  depends_on = [alicloud_vpc.default]
}

locals {
  dms_group = ["0.0.0.0/0"]
  default_group = ["172.16.0.0/16"]

  #################################
  #                               #
  #            databases          #
  #                               #
  #################################

  config = {
    maxmemory-policy  = "volatile-ttl",
    appendonly        = "no",
    notify-keyspace-events        = "Ex"
  }

  accounts = [
    {
      name         = "user1"
      password     = "Test12345"
      privilege = "RoleReadWrite"
      description  = "desp1"
    },
    {
      name         = "user2"
      password     = "Test12345"
      privilege    = "RoleReadOnly"
      description  = "deps2"
    },
    {
      name         = "user3"
      password     = "Test12345"
      privilege    = "RoleRepl"
      description  = "deps3"
    }
  ]

  ###############
  #backup_policy#
  ###############
  backup_period     = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  backup_time       = "03:00Z-04:00Z"

  tags = {
    app = "ebike"
    tenant = "xiaojiu"
    env    = "prod"
  }

}

resource "alicloud_kvstore_instance" "main" {
  instance_class = "redis.master.small.default"
  db_instance_name  = "myredis"
  password       = "Test12345"
  vswitch_id     = alicloud_vswitch.default.id
  security_ips   = concat(local.dms_group, local.default_group)
  vpc_auth_mode  = "Close"
  engine_version = "5.0"
  tags           = local.tags

  config = local.config
}

resource "alicloud_kvstore_backup_policy" "main" {
  instance_id   = alicloud_kvstore_instance.main.id
  backup_time   = local.backup_time
  backup_period = local.backup_period
  depends_on = [alicloud_kvstore_instance.main]
}

resource "alicloud_kvstore_account" "main" {
  count            = length(local.accounts)
  instance_id      = alicloud_kvstore_instance.main.id
  account_name     = lookup(local.accounts[count.index], "name")
  account_password = lookup(local.accounts[count.index], "password")
  description      = lookup(local.accounts[count.index], "description")
  account_privilege= lookup(local.accounts[count.index], "privilege")
  depends_on = [alicloud_kvstore_instance.main]
}

resource "alicloud_kvstore_connection" "main" {
  connection_string_prefix = "allocatetestupdate"
  instance_id              = alicloud_kvstore_instance.main.id
  port                     = 6379
  depends_on = [alicloud_kvstore_instance.main]
}